/**
 * Created by pzs on 2017/10/26.
 *
 * 精算-复核 业务功能模块的服务
 */
var mtOrder = mongoose.model('mtOrder');
var async = require('async');
var Users = mongoose.model('user');
var toolUtil = require('../common/utils/toolUtil');
/* 宝宝树66小区 sprint6 小区大使业绩页面 新增结算历史明细和佣金订单一览页面 add wangcan 20171208 start */
var mtOrderHistory = mongoose.model('mtOrderHistory');
var balance = mongoose.model('mtOrderBalance');
/* 宝宝树66小区 sprint6 小区大使业绩页面 新增结算历史明细和佣金订单一览页面 add wangcan 20171208 end */

var moment = require('moment');

/*宝宝树四期 大使业绩统计的相关计算  pzs 20171031  start**/
// 待结算，待精算：
// 1，根据“结算状态==未结算”“退款状态==未退款”“分享订单佣金归属 || 自购订单佣金归属 || 小区订单佣金归属 || 被邀请大使订单佣金归属”条件查出所有列表数据为List；
// 2，在List里面根据“下单时间小于最近15天”，待结算金额 =（count(分享订单佣金)+count(自购订单佣金)+count（小区订单佣金）+count（被邀请大使佣金））
// 3，在List里面根据“下单时间是最近15天”，待结算金额 =（count(分享订单佣金)+count(自购订单佣金)+count（小区订单佣金）+count（被邀请大使佣金））
exports.getWaitCloseActuarial = function (userId, callback)  {

    //获取75天以前的日期
    // var curtDate  = new Date().getTime();
    // var diffDate = 75*24*60*60*1000; // 75天的时间值
    // var borDate = curtDate-diffDate ; // 75天之前的时间戳
    //
    // var timeCurt =( new Date(curtDate));//.Format('yyyy-MM-dd');
    // var timeBor = (new Date(borDate));//.Format('yyyy-MM-dd');

    //待结算与待精算 处理逻辑是一样的，唯一不一样的地方是查询的时间不同
    var filterUserId = mongoose.Types.ObjectId(userId);
    // var filterUserId = userId;
    // 分享,小区,自购
    var fWaitClose = [
        { '$match' : {
            '$or':[
                {'shareCommissionUser':filterUserId },
                {'selfPurchaseUser':filterUserId },
                {'communityCommissionUser': filterUserId }
            ],
            'balanceStatus' : 2 ,  //待结算==已精算
           // 'order_time': {'$lte':timeBor}
        } },
        {'$group' : {
            '_id' : 0, //无关紧要
            'shareCommission' : {'$sum' : '$shareCommission'},
            'selfPurchase': {'$sum': "$selfPurchase"},
            'communityCommission':{'$sum': '$communityCommission'}
        }
        } ];
    // 邀请
    var fWaitCloseInvator = [
        { '$match' : {
            '$or':[
                {'inviterCommissionUser':filterUserId }
            ],
            'balanceStatus' : 2 ,  //待结算==已精算
            // 'order_time': {'$lte':timeBor}
        } },
        {'$group' : {
            '_id' : 0, //无关紧要
            'inviterCommission':{'$sum': '$inviterCommission'}
        }
        } ];

    var fWaitActuarial = [
        { '$match' : {
            '$or':[
                {'shareCommissionUser':filterUserId },
                {'selfPurchaseUser':filterUserId },
                {'communityCommissionUser': filterUserId }
            ],
            'balanceStatus' : 1,  //待精算== 已粗算
            //'order_time': {'$lte':timeCurt, "$gt":timeBor}
        } },
        {'$group' : {
            '_id' : 0, //无关紧要
            'shareCommission' : {'$sum' : '$shareCommission'},
            'selfPurchase': {'$sum': "$selfPurchase"},
            'communityCommission':{'$sum': '$communityCommission'}
        }
        } ];

    var fWaitActuarialInvator = [
        { '$match' : {
            '$or':[
                {'inviterCommissionUser':filterUserId }
            ],
            'balanceStatus' : 1,  //待精算== 已粗算
            //'order_time': {'$lte':timeCurt, "$gt":timeBor}
        } },
        {'$group' : {
            '_id' : 0, //无关紧要
            'inviterCommission':{'$sum': '$inviterCommission'}
        }
        } ];

    async.series({
        wait_close: function (done) {
            mtOrder.aggregate(fWaitClose).exec(function (error, result){
                if(result && result.length >0){
                    var close = 0;
                    if(result != null && result[0]!= null && result[0].shareCommission != null)
                        close += result[0].shareCommission;
                    if(result != null && result[0]!= null && result[0].selfPurchase != null)
                        close += result[0].selfPurchase;
                    if(result != null && result[0]!= null && result[0].communityCommission != null)
                        close += result[0].communityCommission;
                    mtOrder.aggregate(fWaitCloseInvator).exec(function (error, resultInvator){
                        if(resultInvator!=null && resultInvator[0]!= null && resultInvator[0].inviterCommission != null)
                            close += resultInvator[0].inviterCommission;
                        done(null, close)
                    });
                }
                else{
                    var close = 0;
                    mtOrder.aggregate(fWaitCloseInvator).exec(function (error, resultInvator){
                        if(resultInvator!=null && resultInvator[0]!= null && resultInvator[0].inviterCommission != null)
                            close += resultInvator[0].inviterCommission;
                        done(null, close)
                    });
                    // done(null, close);
                }
            });
        },
        wait_actuarial: function (done) {
            mtOrder.aggregate(fWaitActuarial).exec(function (error, result){
                if(result && result.length >0){
                    var actuarial = 0;
                    if(result != null && result[0]!= null && result[0].shareCommission != null)
                        actuarial += result[0].shareCommission;
                    if(result != null && result[0]!= null && userId && result[0].selfPurchase != null)
                        actuarial += result[0].selfPurchase;
                    if(result != null && result[0]!= null && result[0].communityCommission != null)
                        actuarial += result[0].communityCommission;
                    mtOrder.aggregate(fWaitActuarialInvator).exec(function (error, resultInvator){
                        if(resultInvator!=null && resultInvator[0]!= null && resultInvator[0].inviterCommission != null)
                            actuarial += resultInvator[0].inviterCommission;
                        done(null, actuarial)
                    });
                }
                else{
                    var actuarial = 0;
                    mtOrder.aggregate(fWaitActuarialInvator).exec(function (error, resultInvator){
                        if(resultInvator!=null && resultInvator[0]!= null && resultInvator[0].inviterCommission != null)
                            actuarial += resultInvator[0].inviterCommission;
                        done(null, actuarial)
                    });
                    // done(null, actuarial);
                }
            });
        }
    }, function (error, result) {
        callback(error, result);
    })
}

// 我的购物返佣
// 1，根据“自购订单佣金归属”“退款状态==未退款” 查出所有列表，
// 订单金额（总）=count（单价、拼团价*订单数量）；
// 订单数（总）=count（数量）；
// 佣金（总）=count（自购订单佣金）
exports.getMyShopBrokerage = function (userId, callback) {
   // var filter = {'selfPurchaseUser':userId,  'balanceStatus':{'$ne': 3}};

    var filter = {'selfPurchaseUser':userId,  '$and' : [{'balanceStatus':{'$ne': 3}}, {'balanceStatus':{'$ne': 4}}, {'balanceStatus':{'$ne': 5}}],};
    mtOrder.find( filter, function (error, result){
        if(result){
            var countSum = 0;// 订单金额（总）
            var countMun = 0; //商品数（总）
            var countBrokerage = 0; //佣金（总）

            var tempOrderIdArray = [];
            result.forEach(function(item,index){
                countSum += (item.skuSubTotal * item.skuQuantity);
                // countMun += item.quantity
                countMun++;
                tempOrderIdArray.push(item.order_id);
                countBrokerage += item.selfPurchase
            });
            if(tempOrderIdArray.length > 0) {
                var tempOrderIdCount = toolUtil.arrayDislodgeRepeat(tempOrderIdArray).length;
                logger.debug("我的购物小区大使去重后件数..." + tempOrderIdCount + "@" + userId);
                logger.debug("我的购物小区大使不去重件数..." + tempOrderIdCount + "@" + userId);
                countMun = tempOrderIdCount;
            }

            var date = {'count_sum': countSum, 'count_mun':countMun, 'count_brokerage':countBrokerage}
            callback(error, date);
        }
        else{
            callback(error, null);
        }
    });
}

// 分享购物返佣
// 1，根据“分享订单佣金归属”“退款状态==未退款”查出所有列表，
// 订单金额（总）=count（单价、拼团价*订单数量）；
// 订单数（总）=count（订单数）；
// 佣金（总）=count（分享订单佣金）
exports.getShardShopBrokerage  = function (userId, callback) {
    //userId = mongoose.Types.ObjectId(userId);
    var filter = {'shareCommissionUser':userId ,  '$and' : [{'balanceStatus':{'$ne': 3}}, {'balanceStatus':{'$ne': 4}}, {'balanceStatus':{'$ne': 5}}],};
    mtOrder.find( filter, function (error, result){
        if(result){
            var countSum = 0;// 订单金额（总）
            var countMun = 0; //商品数（总）
            var countBrokerage = 0; //佣金（总）

            var tempOrderIdArray = [];
            result.forEach(function(item,index){
                countSum += (item.skuSubTotal * item.skuQuantity);
                // countMun += item.quantity
                countMun++;
                tempOrderIdArray.push(item.order_id);
                countBrokerage += item.shareCommission;
            });

            if(tempOrderIdArray.length > 0) {
                var tempOrderIdCount = toolUtil.arrayDislodgeRepeat(tempOrderIdArray).length;
                logger.debug("分享购物小区大使去重后件数..." + tempOrderIdCount + "@" + userId);
                logger.debug("分享购物小区大使不去重件数..." + tempOrderIdCount + "@" + userId);
                countMun = tempOrderIdCount;
            }

            var date = {'count_sum': countSum, 'count_mun':countMun, 'count_brokerage':countBrokerage}
            callback(error, date);
        }
        else{
            callback(error, null);
        }
    });
}

// 我的团队返佣列表
// 1，找出邀请人是'我'的所有订单
// 2，找出'我'的团队返佣人员（分享，自购，小区购）
// 3，列出每个人员的订单金额， 订单数，佣金。
exports.getMyTeamBrokerage = function (userId, callback) {
    // var inviterCommissionUser = mongoose.Types.ObjectId(userId);
    var filter = {'inviterCommissionUser' : userId};

    mtOrder.find(filter)
        .sort('order_id')
        .exec(function(error, result){
        var listResult = [];
        var uids = [];
        result.forEach(function(item, index){
            var obj = new Object();
            obj.uId = "";
            if(item.shareCommissionUser){
                obj.uId = item.shareCommissionUser;
            } else if(item.selfPurchaseUser){
                obj.uId = item.selfPurchaseUser;
            } else if(item.communityCommissionUser){
                obj.uId = item.communityCommissionUser;
            }
            if (uids.indexOf(obj.uId.toString()) == -1) {
                uids.push(obj.uId.toString());
            }
            //分享订单佣金，自购订单佣金，小区订单佣金  三者互斥，被邀请大使订单佣金 这个字段可能和其他三个中的一个同时存在
            obj.commission = 0;

            if(item.inviterCommission){
                obj.commission += item.inviterCommission;
            }
            obj.num = 1;
            obj.order_id = item.order_id;
            listResult.push(obj);
        });
            var listResult2 = [];
        for (var i=0; i < uids.length; i++) {
            var tempObj = {num:0, uId:uids[i],nickName:null,commission:0};
            var objAOrderId = "";
            for (var j=0; j < listResult.length; j++) {
                if (uids[i] == listResult[j].uId.toString()) {
                    logger.debug(uids[i] +","+listResult[j].uId.toString()+","+(uids[i] == listResult[j].uId.toString()));
                    tempObj.commission += listResult[j].commission;
                    if (objAOrderId != listResult[j].order_id) {
                        tempObj.num += 1;
                        objAOrderId = listResult[j].order_id
                    }
                }
            }
            listResult2.push(tempObj);
        }

        // for(var i=0; i<listResult.length; i++){
        //     var objA = listResult[i];
        //     var objAOrderId = "";
        //     for(var n=0; n<listResult.length; n++){
        //         var objB = listResult[n];
        //         if( ( i!=n )&& (objA.uId+"" == objB.uId+"")  && (objA.uId+"" !=  "")  ){
        //             if (!objAOrderId == objB.orderId) {
        //                 objA.num += objB.num;
        //                 objAOrderId == objB.orderId;
        //             }
        //             objA.commission +=objB.commission;
        //             objA.uId = "";
        //         }
        //     }
        // }
        // var listResult2 = [];
        // for(var i=0; i<listResult.length; i++){
        //     if(listResult[i].uId+"" != ""){
        //         listResult2.push(listResult[i]);
        //     }
        // }

        var resultData = [];
        //mongoodb 通过聚合拿来的数据，还缺一个昵称，这里通过异步去获取
        var index=0;
        async.eachSeries(listResult2, function (temp, callbackInner) {
                Users.findOne({_id: temp.uId}, 'nickName', function (err, user) {
                    var obj = new Object();
                    obj.num = temp.num;
                    obj.nickName = user.nickName;
                    obj.commission = temp.commission;
                    resultData.push(obj);
                    index++;
                    callbackInner();
                });

        }, function (err) {
            callback(err, resultData);
        });
    });
}


// 我的小区返佣
// 根据“小区订单佣金归属”“退款状态==未退款”查出所有列表，
// 订单金额（总）=count（单价、拼团价*订单数量）；
// 订单数（总）=count（订单数）；
// 佣金（总）=count（我的小区佣金）
exports.getMyCommunityBrokerage = function (userId, callback) {
    var filter = { 'communityCommissionUser':userId ,  '$and' : [{'balanceStatus':{'$ne': 3}}, {'balanceStatus':{'$ne': 4}}, {'balanceStatus':{'$ne': 5}}], };
    mtOrder.find( filter, function (error, result){
        if(result){
            var countSum = 0;// 订单金额（总）
            var countMun = 0; // 商品数（总）
            var countBrokerage = 0; //佣金（总）

            var tempOrderIdArray = [];
            result.forEach(function(item,index){
                countSum += (item.skuSubTotal * item.skuQuantity);
                // countMun += item.quantity;
                tempOrderIdArray.push(item.order_id);
                countMun++;
                countBrokerage += item.communityCommission;
            });

            if(tempOrderIdArray.length > 0) {
                var tempOrderIdCount = toolUtil.arrayDislodgeRepeat(tempOrderIdArray).length;
                logger.debug("我的小区小区大使去重后件数..." + tempOrderIdCount + "@" + userId);
                logger.debug("我的小区小区大使不去重件数..." + tempOrderIdCount + "@" + userId);
                countMun = tempOrderIdCount;
            }

            var date = {'count_sum': countSum, 'count_mun':countMun, 'count_brokerage':countBrokerage};
            callback(error, date);
        }
        else{
            callback(error, null);
        }
    });
}
/*宝宝树四期 大使业绩统计的相关计算  pzs 20171031  end**/

/* 宝宝树66小区 sprint6 小区大使业绩页面 新增结算历史明细和佣金订单一览页面 add wangcan 20171208 start */
// 获取佣金订单一览数据
exports.getCommissionOrderListService = function (ts, token, commType, query, callback) {
    toolUtil.getUserByToken(token, function (err1, user) {
        if (err1) {
            callback(err1, null);
        } else {
            if (user == null) {
                var msg = {
                    "message": noUserErrMessage
                };
                callback(msg, null);
            } else {
                var size = 20;
                var index = Number(ts) * size;
                var option = {};
                var userId = mongoose.Types.ObjectId(user._id);
                if (commType == 'self') {
                    option['selfPurchaseUser'] = userId;
                } else if (commType == 'share') {
                    option['shareCommissionUser'] = userId;
                    // option['shareCommissionUser'] = '595395ac4e8c5b274aa08a1e';
                } else if (commType == 'team') {
                    option['inviterCommissionUser'] = userId;
                } else if (commType == 'community') {
                    option['communityCommissionUser'] = userId;
                }
                logger.debug(option);
                async.waterfall([
                    function (callbackInner) {
                        mtOrder.aggregate([
                            {$match: option},
                            {$match: {$and: [
                                {"balanceStatus": {$ne: 3}},
                                // {"balanceStatus": {$ne: 4}},
                                {"balanceStatus": {$ne: 5}}
                            ]}},
                            {$match: {"status": {$ne: 100}}},
                            {$match: {"isValid": true}},
                            {$group: {_id: "$order_id", count: {$sum: 1}}},
                            {$sort: {_id: -1}},
                            {$skip: index},
                            {$limit: size}
                        ], function (err, orderIdResult) {
                            logger.debug(orderIdResult);
                            callbackInner(err, orderIdResult);
                        });
                    },
                    function (orderIdResult, callbackInner) {
                        if (!orderIdResult || orderIdResult.length == 0) {
                            var msg = {
                                "message": "没有订单数据"
                            };
                            callbackInner(null, msg);
                        } else{
                            var orderList = [];

                            async.eachSeries(orderIdResult, function(obj, callbackInnerInner) {
                                mtOrder.find({"order_id": obj._id.toString()})
                                .populate('order_user', '_id nickName mobilePhone images')
                                .exec(function (err, result) {
                                    if (result) {
                                        var orderObj = {};

                                        // 订单ID
                                        orderObj.orderId = result[0]._doc.order_id;
                                        // 订单时间
                                        orderObj.orderTime = moment(result[0]._doc.order_time).format("YYYY-MM-DD");

                                        var orderSkuList = [];
                                        for (var i = 0, length = result.length; i < length; i++) {
                                            var orderSkuObj = {};
                                            // sku名称
                                            orderSkuObj.skuName = result[i]._doc.sku_name;
                                            // 订单优惠总价
                                            orderSkuObj.skuSubTotal = result[i]._doc.skuSubTotal;
                                            // 下单人
                                            var orderUser = '';
                                            if (result[i]._doc.order_user) {
                                                orderUser = result[i]._doc.order_user._doc.nickName;
                                            }
                                            orderSkuObj.orderUser = orderUser;

                                            // 订单佣金
                                            var orderCommission = 0;
                                            if (result[i]._doc.shareCommission) { // 分享单
                                                orderCommission += result[i]._doc.shareCommission;
                                            } else if (result[i]._doc.selfPurchase) { // 自购单
                                                orderCommission += result[i]._doc.selfPurchase;
                                            } else if (result[i]._doc.communityCommission) { // 小区单
                                                orderCommission += result[i]._doc.communityCommission;
                                            }
                                            // if (result[i]._doc.inviterCommission) { // 邀请单
                                            //     orderCommission += result[i]._doc.inviterCommission;
                                            // }
                                            orderSkuObj.orderCommission = orderCommission;

                                            // 订单状态
                                            orderSkuObj.orderSkuStatus = result[i]._doc.status;

                                            orderSkuList.push(orderSkuObj);
                                        }
                                        orderObj.skuList = orderSkuList;
                                        orderList.push(orderObj);

                                        callbackInnerInner(false);
                                    }
                                });
                            }, function (err) {
                                var tempData = {};
                                if (orderList && orderList.length > 0) {
                                    tempData.list = orderList;
                                    tempData.ts = Number(ts) + 1;
                                }
                                callbackInner(err, tempData);
                            });
                        }
                    }
                ], callback);
            }
        }
    });
}

// 获取团队佣金订单一览数据
exports.getTeamCommissionOrderListService = function (ts, token, commType, query, callback) {
    toolUtil.getUserByToken(token, function (err1, user) {
        if (err1) {
            callback(err1, null);
        } else {
            if (user == null) {
                var msg = {
                    "message": noUserErrMessage
                };
                callback(msg, null);
            } else {
                var size = 20;
                var index = Number(ts) * size;
                var option = {};
                var userId = mongoose.Types.ObjectId(user._id);
                if (commType == 'team') {
                    option['inviterCommissionUser'] = userId;
                }
                logger.debug(option);
                async.waterfall([
                    function (callbackInner) {
                        mtOrder.aggregate([
                            {$match: option},
                            {$match: {$and: [
                                {"balanceStatus": {$ne: 4}},
                                {"balanceStatus": {$ne: 5}}
                            ]}},
                            {$match: {"status": {$ne: 100}}},
                            {$match: {"isValid": true}},
                            {$group: {_id: {
                                "selfPurchaseUser": "$selfPurchaseUser",
                                "communityCommissionUser": "$communityCommissionUser",
                                "shareCommissionUser": "$shareCommissionUser"
                            }, count: {$sum: 1}}},
                            {$sort: {_id: -1}},
                            {$skip: index},
                            {$limit: size}
                        ], function (err, commUserRes) {
                            logger.debug("订单佣金归属人。。。" + commUserRes);
                            logger.debug("订单数量。。。" + commUserRes.length);
                            callbackInner(err, commUserRes);
                        });
                    },
                    function (commUserRes, callbackInner) {
                        if (!commUserRes || commUserRes.length == 0) {
                            var msg = {
                                "message": "没有订单数据"
                            };
                            callbackInner(null, msg);
                        } else{
                            var teamList = []; // 我的团队列表

                            async.eachSeries(commUserRes, function(obj, callbackInnerInner) {
                                var opt4MyTeam = {
                                    "inviterCommissionUser": userId,
                                    $and: [
                                        {"balanceStatus": {$ne: 4}},
                                        {"balanceStatus": {$ne: 5}}
                                    ],
                                    "status": {$ne: 100},
                                    "isValid": true
                                };
                                if (obj._id.selfPurchaseUser) {
                                    opt4MyTeam['selfPurchaseUser'] = obj._id.selfPurchaseUser;
                                } else if (obj._id.communityCommissionUser) {
                                    opt4MyTeam['communityCommissionUser'] = obj._id.communityCommissionUser;
                                } else if (obj._id.shareCommissionUser) {
                                    opt4MyTeam['shareCommissionUser'] = obj._id.shareCommissionUser;
                                }
                                mtOrder.find(opt4MyTeam)
                                    .populate('order_user', '_id nickName mobilePhone images')
                                    .populate('selfPurchaseUser', '_id nickName mobilePhone images')
                                    .populate('communityCommissionUser', '_id nickName mobilePhone images')
                                    .populate('shareCommissionUser', '_id nickName mobilePhone images')
                                    .sort('-order_id')
                                    .exec(function (err, result) {
                                        if (result) {
                                            var teamObj = {};
                                            teamObj.commBelongerUser = '';
                                            if (result[0]._doc.selfPurchaseUser) {
                                                teamObj.commBelongerUser = result[0]._doc.selfPurchaseUser._doc.nickName;
                                            } else if (result[0]._doc.communityCommissionUser) {
                                                teamObj.commBelongerUser = result[0]._doc.communityCommissionUser._doc.nickName;
                                            } else if (result[0]._doc.shareCommissionUser) {
                                                teamObj.commBelongerUser = result[0]._doc.shareCommissionUser._doc.nickName;
                                            }
                                            var orderList = []; // 订单列表
                                            var orderIds = []; // 订单id 数组
                                            // 获取所有订单id
                                            for (var i = 0, length = result.length; i < length; i++) {
                                                orderIds.push(result[i]._doc.order_id);
                                            }
                                            // 订单id去重
                                            var tempOrderIds = toolUtil.arrayDislodgeRepeat(orderIds);

                                            if (tempOrderIds && tempOrderIds.length > 0) {
                                                for (var i = 0, length = tempOrderIds.length; i < length; i++) {

                                                    var orderSkuList = []; // 订单商品列表
                                                    // 订单列表数据
                                                    var orderObj = {};

                                                    for (var j = 0, len = result.length; j < len; j++) {
                                                        if (tempOrderIds[i] == result[j]._doc.order_id) {
                                                            // 订单列表数据
                                                            // 订单ID
                                                            orderObj.orderId = result[j]._doc.order_id;
                                                            // 订单时间
                                                            orderObj.orderTime = moment(result[j]._doc.order_time).format("YYYY-MM-DD");

                                                            // 订单商品列表数据
                                                            var orderSkuObj = {};
                                                            // sku名称
                                                            orderSkuObj.skuName = result[j]._doc.sku_name;
                                                            // 订单优惠总价
                                                            orderSkuObj.skuSubTotal = result[j]._doc.skuSubTotal;
                                                            // 下单人
                                                            orderSkuObj.orderUser = '';
                                                            if (result[j]._doc.order_user) {
                                                                orderSkuObj.orderUser = result[j]._doc.order_user._doc.nickName;
                                                            }

                                                            // 订单佣金
                                                            orderSkuObj.orderCommission = 0;
                                                            // if (result[j]._doc.shareCommission) { // 分享单
                                                            //     orderSkuObj.orderCommission += result[j]._doc.shareCommission;
                                                            // } else if (result[j]._doc.selfPurchase) { // 自购单
                                                            //     orderSkuObj.orderCommission += result[j]._doc.selfPurchase;
                                                            // } else if (result[j]._doc.communityCommission) { // 小区单
                                                            //     orderSkuObj.orderCommission += result[j]._doc.communityCommission;
                                                            // }
                                                            if (result[j]._doc.inviterCommission) { // 邀请单
                                                                orderSkuObj.orderCommission += result[j]._doc.inviterCommission;
                                                            }
                                                            // 订单状态
                                                            orderSkuObj.orderSkuStatus = result[j]._doc.status;

                                                            orderSkuList.push(orderSkuObj);
                                                            orderObj.orderSkuList = orderSkuList;
                                                        }
                                                    }
                                                    orderList.push(orderObj);
                                                }
                                            }

                                            teamObj.orderList = orderList;
                                            teamList.push(teamObj);

                                            callbackInnerInner(false);
                                        }
                                    });
                            }, function (err) {
                                var tempData = {};
                                if (teamList && teamList.length > 0) {
                                    tempData.list = teamList;
                                    tempData.ts = Number(ts) + 1;
                                }
                                callbackInner(err, tempData);
                            });
                        }
                    }
                ], callback);
            }
        }
    });
}

// 获取佣金订单详情
// exports.getCommissionOrderDetailService = function (token, orderId, query, callback) {
//     mtOrder.findOne({'order_id': orderId})
//         .populate('order_user', '_id nickName mobilePhone images').exec(function (err, result) {
//         if (result) {
//             var data = {};
//             // 记录ID
//             data.id = result._doc.id;
//             // sku LOGO
//             data.prdLogo = "http://img01sit.meituncdn.com/group1/M00/CE/28/1c3536ef48284ce38393ce322785cca2.jpg";
//             // sku名称
//             data.skuName = result._doc.sku_name;
//             // 商品单价
//             data.price = result._doc.price;
//             // 订单优惠总价
//             data.skuSubTotal = result._doc.skuSubTotal;
//             // sku数量
//             data.skuQuantity = result._doc.skuQuantity;
//             // 是否海淘
//             data.wavesSign = result._doc.wavesSign;
//             // 是否自营
//             data.itemSaleType = result._doc.itemSaleType;
//             // 是否标品
//             data.standard = result._doc.standard;
//             // 商品类目佣金比例
//             data.commissionPercent = (result._doc.commissionPercent * 100).toFixed(2) + "%";
//             // 下单日期
//             data.orderTime = moment(result._doc.order_time).format('YYYY-MM-DD');
//             // 是否退款
//             data.isRefund = result._doc.refundStatus ? '是' : '否';
//             // 退款时间
//             data.refundTime = result._doc.refundTime;
//             // 下单人
//             var orderUser = result._doc.order_user;
//             data.orderUser = orderUser ? orderUser._doc.nickName : '';
//
//             // 商品类型
//             var itemSaleTypeName = result._doc.itemSaleType ? toolUtil.getItemSaleTypeName(result._doc.itemSaleType) : '';
//             var wavesSignName = result._doc.wavesSign ? toolUtil.getWavesSignName(result._doc.wavesSign) : '';
//             var standardName = result._doc.standard ? toolUtil.getStandardName(result._doc.standard) : '';
//
//             data.skuType = itemSaleTypeName + " " + wavesSignName + " " + standardName;
//
//             // 订单佣金计算
//             var orderCommission = 0;
//             if (result._doc.shareCommission) {
//                 orderCommission += result._doc.shareCommission;
//             } else if (result._doc.selfPurchase) {
//                 orderCommission += result._doc.selfPurchase;
//             } else if (result._doc.communityCommission) {
//                 orderCommission += result._doc.communityCommission;
//             }
//             if (result._doc.inviterCommission) {
//                 orderCommission += result._doc.inviterCommission;
//             }
//             // 订单佣金
//             data.orderCommission = orderCommission;
//
//             // 佣金类型
//             var commType = '';
//             if (result._doc.shareCommissionUser) {
//                 commType = '分享' + ' ';
//             } else if (result._doc.selfPurchaseUser) {
//                 commType += '自购' + ' ';
//             } else if (result._doc.communityCommissionUser) {
//                 commType += '小区' + ' ';
//             }
//             if (result._doc.inviterCommissionUser) {
//                 commType += '邀请';
//             }
//             data.commissionType = commType.trim();
//             // commType = result._doc.orderCommissionType ? toolUtil.getOrderCommissionTypeName(result._doc.orderCommissionType) : '';
//             // if (result._doc.isInviterCommissionStatus) {
//             //     commType += ' ' + '团队';
//             // }
//             // data.commissionType = commType;
//
//             callback(null, data);
//         } else {
//             callback(err, null);
//         }
//     });
// }

// 获取结算历史一览数据
exports.getBalanceHistoryListService = function (ts, token, query, callback) {
    toolUtil.getUserByToken(token, function (err1, user) {
        if (err1) {
            callback(err1, null);
        } else {
            if (user == null) {
                var msg = {
                    "message": noUserErrMessage
                };
                callback(msg, null);
            } else {
                var size = 20;
                var index = Number(ts) * size;
                var hasNextPage = 0; // 是否有下一页数据 0-没有 1-有
                var userId = mongoose.Types.ObjectId(user._id);
                async.waterfall([
                    function (callbackInner) {
                        balance.find({
                            "balanceAmbassadorUser": userId,
                            "isValid": true
                        }).populate('balanceAmbassadorUser', '_id nickName mobilePhone images')
                        .sort('-balance_time').exec(function (err, balanceRes) {
                            if (err) {
                                callbackInner(err, null);
                            } else {
                                logger.debug(balanceRes);
                                var yearArr = [];
                                if (balanceRes && balanceRes.length > 0) {
                                    // 临时数组--保存结算时间的年份数据
                                    var tempArr = [];
                                    for (var i = 0, length = balanceRes.length; i < length; i++) {
                                        tempArr.push(moment(balanceRes[i]._doc.balance_time).format("YYYY"));
                                    }
                                    // 数组去重--去除重复的年份
                                    yearArr = toolUtil.arrayDislodgeRepeat(tempArr);
                                }

                                if (yearArr && yearArr.length > 0) {
                                    if (yearArr.length > size) {
                                        // 取得每一页要显示的数据中的第一行数据的年份
                                        // var tempYear = '';
                                        var tempCount = 0;
                                        var tempYear = yearArr[index];
                                        if (yearArr.length >= (Number(ts) + 1) * size) {
                                            tempCount = size;
                                            hasNextPage = 1;
                                        } else {
                                            // tempYear = yearArr[index];
                                            tempCount = yearArr.length - Number(ts) * size;
                                            hasNextPage = 0;
                                        }

                                        // 取出当前页要显示的size个数据
                                        var balanceObjArr = [];
                                        for (var i = 0; i < tempCount; i++) {
                                            var nextYear = (Number(tempYear) - i).toString();
                                            for (var j = 0, length = balanceRes.length; j < length; j++) {
                                                if (moment(balanceRes[j]._doc.balance_time).format("YYYY") == nextYear) {
                                                    balanceObjArr.push(balanceRes[j]);
                                                }
                                            }
                                        }
                                        callbackInner(null, balanceObjArr);
                                    } else {
                                        hasNextPage = 0;
                                        callbackInner(null, balanceRes);
                                    }
                                } else {
                                    hasNextPage = 0;
                                    callbackInner(null, balanceRes);
                                }
                            }
                        });
                    },
                    function (balanceRes, callbackInner) {
                        if (!balanceRes || balanceRes.length == 0) {
                            callbackInner(null, {"message": "没有结算数据"});
                        } else{
                            var balanceHisYearList = []; // 结算历史年份列表数据

                            async.eachSeries(balanceRes, function(obj, callbackInnerInner) {
                                mtOrderHistory.find({"balance_id": obj._doc._id.toString()}, function (err, orderHisRes) {
                                    if (!orderHisRes) {
                                        callbackInnerInner(null, {"message": "获取结算历史订单列表数据失败"});
                                    } else {
                                        var balanceYearObj = {};
                                        // 结算年份
                                        var balanceDateYear = moment(obj._doc.balance_time).format("YYYY");
                                        balanceYearObj.balanceDateYear = balanceDateYear;

                                        var balanceMonthObj = {};
                                        // 结算记录id
                                        balanceMonthObj.balanceId = obj._doc._id.toString();
                                        // 结算大使id
                                        balanceMonthObj.balanceAmbUser = obj._doc.balanceAmbassadorUser;
                                        // 结算时间
                                        // balanceMonthObj.balanceDate = moment(obj._doc.balance_time).format("YYYY-MM-DD");
                                        balanceMonthObj.balanceDateMonth = moment(obj._doc.balance_time).format("MM月");
                                        // 结算佣金
                                        balanceMonthObj.balanceCommission = obj._doc.balanceCommission;
                                        // 结算订单数量
                                        var tempArr = [];
                                        // 订单总金额
                                        var orderTotalPrice = 0;
                                        for (var i = 0, length = orderHisRes.length; i < length; i++) {
                                            tempArr.push(orderHisRes[i]._doc.order_id);
                                            orderTotalPrice +=  orderHisRes[i]._doc.skuSubTotal;
                                        }
                                        balanceMonthObj.orderTotalPrice = orderTotalPrice.toFixed(2);
                                        // 数组去重后的长度为结算订单数量
                                        balanceMonthObj.balanceOrderTotals = toolUtil.arrayDislodgeRepeat(tempArr).length;
                                        // balanceHisMonthList.push(balanceMonthObj);

                                        // 设置结算年份列表数据
                                        if (balanceHisYearList && balanceHisYearList.length > 0) {
                                            var isYearExist = false; // 是否存在当年数据
                                            var yearIndex = 0; // 当年数据在结算年份列表数据中的位置
                                            for (var i = 0, length = balanceHisYearList.length; i < length; i++) {
                                                if (balanceDateYear == balanceHisYearList[i].balanceDateYear) {
                                                    isYearExist = true;
                                                    yearIndex = i;
                                                    break;
                                                }
                                            }
                                            if (isYearExist) {
                                                balanceHisYearList[yearIndex].balanceHisMonthList.push(balanceMonthObj);
                                            } else {
                                                var balanceHisMonthList = []; // 结算历史月份列表数据
                                                balanceHisMonthList.push(balanceMonthObj);

                                                balanceYearObj.balanceHisMonthList = balanceHisMonthList;
                                                balanceHisYearList.push(balanceYearObj);
                                            }
                                        } else {
                                            var balanceHisMonthList = []; // 结算历史月份列表数据
                                            balanceHisMonthList.push(balanceMonthObj);

                                            balanceYearObj.balanceHisMonthList = balanceHisMonthList;
                                            balanceHisYearList.push(balanceYearObj);
                                        }

                                        callbackInnerInner(false);
                                    }
                                });
                            }, function (err) {
                                var tempData = {};
                                if (balanceHisYearList && balanceHisYearList.length > 0) {
                                    tempData.list = balanceHisYearList;
                                    tempData.ts = Number(ts) + 1;
                                    tempData.hasNextPage = hasNextPage;
                                }
                                callbackInner(err, tempData);
                            });
                        }
                    }
                ], callback);
            }
        }
    });
}

// 获取结算历史订单一览数据
// exports.getBalanceHisOrderListService = function (ts, token, balanceId, balanceAmbUserId, query, callback) {
//     toolUtil.getUserByToken(token, function (err1, user) {
//         if (err1) {
//             callback(err1, null);
//         } else {
//             if (user == null) {
//                 var msg = {
//                     "message": noUserErrMessage
//                 };
//                 callback(msg, null);
//             } else {
//                 var size = 5;
//                 var index = Number(ts) * size;
//                 var option = {};
//                 var userId = mongoose.Types.ObjectId(user._id);
//                 logger.debug(option);
//
//                 async.waterfall([
//                     function (callbackInner) {
//                         mtOrderHistory.aggregate([
//                             {$match: {"balance_id": mongoose.Types.ObjectId(balanceId)}},
//                             {$match: {$or: [
//                                 {"balanceStatus": 3},
//                                 {"balanceStatus": 4},
//                                 {"balanceStatus": 5}
//                             ]}},
//                             {$match: {"status": {$ne: 100}}},
//                             {$match: {"isValid": true}},
//                             {$group: {_id: "$order_id", count: {$sum: 1}}},
//                             {$sort: {_id: -1}},
//                             {$skip: index},
//                             {$limit: size}
//                         ], function (err, orderIdResult) {
//                             logger.debug(orderIdResult);
//                             callbackInner(null, orderIdResult);
//                         });
//                     },
//                     function (orderIdResult, callbackInner) {
//                         if (!orderIdResult || orderIdResult.length == 0) {
//                             callbackInner(null, null);
//                         } else{
//                             var list = [];
//
//                             async.eachSeries(orderIdResult, function(obj, callbackInnerInner) {
//                                 mtOrderHistory.find({"order_id": obj._id.toString()}, function (err, result) {
//                                     if (result) {
//                                         var orderObj = {};
//                                         // 订单记录ID
//                                         orderObj.orderId = result[0]._doc.order_id;
//                                         // sku名称
//                                         var skuName = '';
//                                         for (var i = 0, length = result.length; i < length; i++) {
//                                             if (i) {
//                                                 skuName += '/' + result[i]._doc.sku_name;
//                                             } else {
//                                                 skuName += result[i]._doc.sku_name;
//                                             }
//                                         }
//                                         orderObj.skuName = skuName;
//                                         // 订单商品总价
//                                         orderObj.total = result[0]._doc.total;
//                                         // 订单优惠总价
//                                         orderObj.skuSubTotal = result[0]._doc.skuSubTotal;
//                                         // 订单商品数量
//                                         orderObj.skuQuantity = result[0]._doc.quantity;
//                                         // sku LOGO
//                                         orderObj.prdLogo = 'http://img01sit.meituncdn.com/group1/M00/CE/28/1c3536ef48284ce38393ce322785cca2.jpg';
//
//                                         // 订单佣金
//                                         var orderCommission = 0;
//                                         for (var i = 0, length = result.length; i < length; i++) {
//                                             if (result[i]._doc.shareCommission) { // 分享单
//                                                 orderCommission += result[i]._doc.shareCommission;
//                                             } else if (result[i]._doc.selfPurchase) { // 自购单
//                                                 orderCommission += result[i]._doc.selfPurchase;
//                                             } else if (result[i]._doc.communityCommission) { // 小区单
//                                                 orderCommission += result[i]._doc.communityCommission;
//                                             }
//                                             if (result[i]._doc.inviterCommission) { // 邀请单
//                                                 orderCommission += result[i]._doc.inviterCommission;
//                                             }
//                                         }
//                                         orderObj.orderCommission = orderCommission;
//                                         list.push(orderObj);
//
//                                         callbackInnerInner(false);
//                                     }
//                                 });
//                             }, function (err) {
//                                 var tempData = {};
//                                 if (list && list.length > 0) {
//                                     tempData.list = list;
//                                     tempData.ts = Number(ts) + 1;
//                                 }
//                                 callbackInner(err, tempData);
//                             });
//                         }
//                     }
//                 ], callback);
//
//                 // async.waterfall([
//                 //     function (callbackInner) {
//                 //         mtOrder.aggregate([
//                 //             {$match: option},
//                 //             {$match: {$and: [
//                 //                 {"balanceStatus": {$ne: 3}},
//                 //                 {"balanceStatus": {$ne: 4}},
//                 //                 {"balanceStatus": {$ne: 5}}
//                 //             ]}},
//                 //             {$match: {"status": {$ne: 100}}},
//                 //             {$match: {"isValid": true}},
//                 //             {$group: {_id: "$order_id", count: {$sum: 1}}},
//                 //             {$sort: {_id: -1}},
//                 //             {$skip: index},
//                 //             {$limit: size}
//                 //         ], function (err, orderIdResult) {
//                 //             logger.debug(orderIdResult);
//                 //             callbackInner(null, orderIdResult);
//                 //         });
//                 //     },
//                 //     function (orderIdResult, callbackInner) {
//                 //         if (!orderIdResult || orderIdResult.length == 0) {
//                 //             callbackInner(null, null);
//                 //         } else{
//                 //             var list = [];
//                 //
//                 //             async.eachSeries(orderIdResult, function(obj, callbackInnerInner) {
//                 //                 mtOrder.find({"order_id": obj._id.toString()}, function (err, result) {
//                 //                     if (result) {
//                 //                         var orderObj = {};
//                 //                         // 订单记录ID
//                 //                         orderObj.orderId = result[0]._doc.order_id;
//                 //                         // sku名称
//                 //                         var skuName = '';
//                 //                         for (var i = 0, length = result.length; i < length; i++) {
//                 //                             if (i) {
//                 //                                 skuName += '/' + result[i]._doc.sku_name;
//                 //                             } else {
//                 //                                 skuName += result[i]._doc.sku_name;
//                 //                             }
//                 //                         }
//                 //                         orderObj.skuName = skuName;
//                 //                         // 订单商品总价
//                 //                         orderObj.total = result[0]._doc.total;
//                 //                         // 订单优惠总价
//                 //                         orderObj.skuSubTotal = result[0]._doc.skuSubTotal;
//                 //                         // 订单商品数量
//                 //                         orderObj.skuQuantity = result[0]._doc.quantity;
//                 //                         // sku LOGO
//                 //                         orderObj.prdLogo = 'http://img01sit.meituncdn.com/group1/M00/CE/28/1c3536ef48284ce38393ce322785cca2.jpg';
//                 //
//                 //                         // 订单佣金
//                 //                         var orderCommission = 0;
//                 //                         for (var i = 0, length = result.length; i < length; i++) {
//                 //                             if (result[i]._doc.shareCommission) { // 分享单
//                 //                                 orderCommission += result[i]._doc.shareCommission;
//                 //                             } else if (result[i]._doc.selfPurchase) { // 自购单
//                 //                                 orderCommission += result[i]._doc.selfPurchase;
//                 //                             } else if (result[i]._doc.communityCommission) { // 小区单
//                 //                                 orderCommission += result[i]._doc.communityCommission;
//                 //                             }
//                 //                             if (result[i]._doc.inviterCommission) { // 邀请单
//                 //                                 orderCommission += result[i]._doc.inviterCommission;
//                 //                             }
//                 //                         }
//                 //                         orderObj.orderCommission = orderCommission;
//                 //                         list.push(orderObj);
//                 //
//                 //                         callbackInnerInner(false);
//                 //                     }
//                 //                 });
//                 //             }, function (err) {
//                 //                 var tempData = {};
//                 //                 if (list && list.length > 0) {
//                 //                     tempData.list = list;
//                 //                     tempData.ts = Number(ts) + 1;
//                 //                 }
//                 //                 callbackInner(err, tempData);
//                 //             });
//                 //         }
//                 //     }
//                 // ], callback);
//             }
//         }
//     });
// }

// 结算历史明细--小区订单
exports.getMyCommunityBalanceHisBrokerage = function (userId, balanceId, callback) {
    var filter = {
        'communityCommissionUser':userId ,
        'balance_id': balanceId,
        '$or' : [
            {'balanceStatus': 3},
            {'balanceStatus': 4},
            {'balanceStatus': 5}
        ],
        'status': {$ne: 100},
        'isValid': true
    };
    mtOrderHistory.find( filter, function (error, result){
        if(result){
            var countSum = 0;// 订单金额（总）
            var countMun = 0; // 订单数（总）
            var countBrokerage = 0; //佣金（总）

            var tempOrderIdArray = [];
            result.forEach(function(item,index){
                countSum += item.skuSubTotal;
                tempOrderIdArray.push(item.order_id);
                countBrokerage += item.communityCommission;
            });

            if(tempOrderIdArray.length > 0) {
                var tempOrderIdCount = toolUtil.arrayDislodgeRepeat(tempOrderIdArray).length;
                logger.debug("我的小区结算历史订单去重后件数..." + tempOrderIdCount + "...@" + userId);
                logger.debug("我的小区结算历史订单不去重件数..." + tempOrderIdArray.length + "...@" + userId);
                countMun = tempOrderIdCount;
            }

            var date = {'count_sum': countSum, 'count_mun':countMun, 'count_brokerage':countBrokerage};
            callback(null, date);
        }
        else{
            callback(error, null);
        }
    });
}

// 结算历史明细--自购订单
exports.getMyShopBalanceHisBrokerage = function (userId, balanceId, callback) {
    var filter = {
        'selfPurchaseUser':userId,
        'balance_id': balanceId,
        '$or' : [
            {'balanceStatus': 3},
            {'balanceStatus': 4},
            {'balanceStatus': 5}
        ],
        'status': {$ne: 100},
        'isValid': true
    };
    mtOrderHistory.find( filter, function (error, result){
        if(result){
            var countSum = 0;// 订单金额（总）
            var countMun = 0; // 订单数（总）
            var countBrokerage = 0; // 佣金（总）

            var tempOrderIdArray = [];
            result.forEach(function(item,index){
                countSum += item.skuSubTotal;
                tempOrderIdArray.push(item.order_id);
                countBrokerage += item.selfPurchase
            });
            if(tempOrderIdArray.length > 0) {
                var tempOrderIdCount = toolUtil.arrayDislodgeRepeat(tempOrderIdArray).length;
                logger.debug("我的购物结算历史订单去重后件数..." + tempOrderIdCount + "...@" + userId);
                logger.debug("我的购物结算历史订单不去重件数..." + tempOrderIdArray.length + "...@" + userId);
                countMun = tempOrderIdCount;
            }

            var date = {'count_sum': countSum, 'count_mun':countMun, 'count_brokerage':countBrokerage}
            callback(null, date);
        }
        else{
            callback(error, null);
        }
    });
}

// 结算历史明细--团队订单
exports.getMyTeamBalanceHisBrokerage = function (userId, balanceId, callback) {
    var filter = {
        'inviterCommissionUser' : userId,
        'balance_id': balanceId,
        '$or' : [
            {'balanceStatus': 3},
            {'balanceStatus': 4},
            {'balanceStatus': 5}
        ],
        'status': {$ne: 100},
        'isValid': true
    };

    mtOrderHistory.find(filter)
        .sort('order_id')
        .exec(function(error, result){
            var listResult = [];
            var uids = [];
            result.forEach(function(item, index){
                var obj = new Object();
                obj.uId = "";
                if(item.shareCommissionUser){
                    obj.uId = item.shareCommissionUser;
                } else if(item.selfPurchaseUser){
                    obj.uId = item.selfPurchaseUser;
                } else if(item.communityCommissionUser){
                    obj.uId = item.communityCommissionUser;
                }
                if (uids.indexOf(obj.uId.toString()) == -1) {
                    uids.push(obj.uId.toString());
                }
                //分享订单佣金，自购订单佣金，小区订单佣金  三者互斥，被邀请大使订单佣金 这个字段可能和其他三个中的一个同时存在
                obj.commission = 0;

                if(item.inviterCommission){
                    obj.commission += item.inviterCommission;
                }
                obj.num = 1;
                obj.order_id = item.order_id;
                listResult.push(obj);
            });
            var listResult2 = [];
            for (var i=0; i < uids.length; i++) {
                var tempObj = {num:0, uId:uids[i],nickName:null,commission:0};
                var objAOrderId = "";
                for (var j=0; j < listResult.length; j++) {
                    if (uids[i] == listResult[j].uId.toString()) {
                        logger.debug(uids[i] +","+listResult[j].uId.toString()+","+(uids[i] == listResult[j].uId.toString()));
                        tempObj.commission += listResult[j].commission;
                        if (objAOrderId != listResult[j].order_id) {
                            tempObj.num += 1;
                            objAOrderId = listResult[j].order_id
                        }
                    }
                }
                listResult2.push(tempObj);
            }

            var resultData = [];
            //mongoodb 通过聚合拿来的数据，还缺一个昵称，这里通过异步去获取
            var index=0;
            async.eachSeries(listResult2, function (temp, callbackInner) {
                Users.findOne({_id: temp.uId}, 'nickName', function (err, user) {
                    var obj = new Object();
                    obj.num = temp.num;
                    obj.nickName = user.nickName;
                    obj.commission = temp.commission;
                    resultData.push(obj);
                    index++;
                    callbackInner();
                });

            }, function (err) {
                callback(err, resultData);
            });
        });
}

// 结算历史明细--分享订单
exports.getShardShopBalanceHisBrokerage  = function (userId, balanceId, callback) {
    //userId = mongoose.Types.ObjectId(userId);
    var filter = {
        'shareCommissionUser': userId,
        'balance_id': balanceId,
        '$or' : [
            {'balanceStatus': 3},
            {'balanceStatus': 4},
            {'balanceStatus': 5}
        ],
        'status': {$ne: 100},
        'isValid': true
    };
    mtOrderHistory.find( filter, function (error, result){
        if(result){
            var countSum = 0;// 订单金额（总）
            var countMun = 0; // 订单数（总）
            var countBrokerage = 0; // 佣金（总）

            var tempOrderIdArray = [];
            result.forEach(function(item,index){
                countSum += item.skuSubTotal;
                tempOrderIdArray.push(item.order_id);
                countBrokerage += item.shareCommission;
            });

            if(tempOrderIdArray.length > 0) {
                var tempOrderIdCount = toolUtil.arrayDislodgeRepeat(tempOrderIdArray).length;
                logger.debug("分享购物结算历史订单去重后件数..." + tempOrderIdCount + "...@" + userId);
                logger.debug("分享购物结算历史订单不去重件数..." + tempOrderIdArray.length + "...@" + userId);
                countMun = tempOrderIdCount;
            }

            var date = {'count_sum': countSum, 'count_mun':countMun, 'count_brokerage':countBrokerage}
            callback(error, date);
        }
        else{
            callback(error, null);
        }
    });
}
/* 宝宝树66小区 sprint6 小区大使业绩页面 新增结算历史明细和佣金订单一览页面 add wangcan 20171208 end */
